package com.xindaoapp.happypet;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.umeng.analytics.MobclickAgent;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.Constants.NoticeLabel;

public class MainActivity extends SlidingFragmentActivity implements OnClickListener {
    // 初始化Fragement标签
    private LeftMenuFragement leftMenuFragement;
    private RightMenuFragement rightMenuFragement;
    private Fragment[] mFragments;
    private FragmentManager manager;
    private FragmentTransaction transaction;

    private SlidingMenu menu;
    private View[] vTabViews;
    private View vAttentionLabelIcon;
    private NoticeReceiver mNoticeReceiver;
    /** 消息推送底部tab红点标记 */
    private View vNoticeMessageLabelIcon;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBehindContentView(R.layout.left_menu_frame);
        setContentView(R.layout.main_frame);
        manager = getSupportFragmentManager();
        transaction = manager.beginTransaction();
        mFragments =
                new Fragment[] {manager.findFragmentById(R.id.club),
                        manager.findFragmentById(R.id.fx), manager.findFragmentById(R.id.shop),
                        manager.findFragmentById(R.id.message), manager.findFragmentById(R.id.wd)};
        // 初始化View
        initView();
        // 初始化SlidingMenu
        initSlidingMenu(savedInstanceState);
        CommonUtil.checkUpdate(this);
    }

    /**
     * //初始化SlidingMenu
     * 
     * @param savedInstanceState
     */
    private void initSlidingMenu(Bundle savedInstanceState) {
        menu = getSlidingMenu();
        menu.setShadowWidthRes(R.dimen.shadow_width);
        menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        menu.setFadeDegree(0.35f);
        getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);

        menu.setSecondaryMenu(R.layout.right_menu_frame);
        if (savedInstanceState == null) {
            leftMenuFragement = new LeftMenuFragement();
            rightMenuFragement = new RightMenuFragement();
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.left_menu_frame, leftMenuFragement, "LeftMenu").commit();
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.right_menu_frame, rightMenuFragement, "RightMenu").commit();

        }
        menu.setMode(SlidingMenu.LEFT);
    }

    /**
     * //初始化View
     */
    private void initView() {
        vTabViews =
                new View[] {findViewById(R.id.main_club), findViewById(R.id.main_fx),
                        findViewById(R.id.main_shop), findViewById(R.id.main_message),
                        findViewById(R.id.main_wd)};

        for (View view : vTabViews) {
            view.setOnClickListener(this);
        }
        vNoticeMessageLabelIcon = findViewById(R.id.message_notice);
        vAttentionLabelIcon = findViewById(R.id.iv_push);
        vAttentionLabelIcon.setOnClickListener(this);

        mNoticeReceiver = new NoticeReceiver();
        registerReceiver(mNoticeReceiver, new IntentFilter(Constants.KEY_NOTICE_STATE_CHANGED));

        setTabSelected(0);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getPackageName());
        MobclickAgent.onPause(this);
        JPushInterface.onPause(getBaseContext());
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(getPackageName());
        MobclickAgent.onResume(this);
        JPushInterface.onResume(getBaseContext());
    }

    /**
     * 设置底部Tab切换和页面切换
     * 
     * @param position 点击的下标
     */
    private void setTabSelected(int position) {
        transaction = manager.beginTransaction();
        for (int i = 0; i < mFragments.length; i++) {
            if (i == position) {
                vTabViews[i].setSelected(true);
                transaction.show(mFragments[i]);
            } else {
                vTabViews[i].setSelected(false);
                transaction.hide(mFragments[i]);
            }
        }
        transaction.commit();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_club:
                setTabSelected(0);
                break;
            case R.id.main_fx:
                setTabSelected(1);
                break;
            case R.id.main_shop:
                setTabSelected(2);
                break;
            case R.id.main_message:
                if (UserState.isLogged(MainActivity.this)) {
                    setTabSelected(3);
                }
                break;
            case R.id.main_wd:
                setTabSelected(4);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mNoticeReceiver);
    }

    private long firstTime = 0;

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) { // 如果两次按键时间间隔大于2秒，则不退出
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    firstTime = secondTime;// 更新firstTime
                    return true;
                } else { // 两次按键小于2秒时，退出应用
                    System.exit(0);
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    class NoticeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (NoticeLabel.sHasNewMessageNotice) {
                vNoticeMessageLabelIcon.setVisibility(View.VISIBLE);
            } else {
                vNoticeMessageLabelIcon.setVisibility(View.GONE);
            }
        }

    }

}
